package org.zqh.mvc;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.zqh.mvc.action.Action;
import org.zqh.mvc.form.ActionForm;

/**
 * 统一的入口
*    
* 项目名称：zqhmvc   
* 类名称：ActionServlet   
* 类描述：   
* 创建人：zhangqh   
* 创建时间：2015年5月22日 下午11:28:51   
* 修改人：zhangqh  
* 修改时间：2015年5月22日 下午11:28:51   
* 修改备注：   
* @version    
*
 */
public class ActionServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String path = req.getServletPath().split("\\.")[0];
		Map<String, ActionMapping> map = (Map<String, ActionMapping>) this.getServletContext().getAttribute("zqhmvc");
		ActionMapping mxc = map.get(path);
		String url = "";
		if (mxc != null) {
			ActionForm form = null;
			Action action = null;
			try {
				Class clazz = Class.forName(mxc.getName());
				form = (ActionForm) clazz.newInstance();
				Field[] fields = clazz.getDeclaredFields();

				for (Field f : fields) {
					f.setAccessible(true);
					f.set(form, req.getParameter(f.getName()));
					f.setAccessible(false);
				}
				clazz = Class.forName(mxc.getType());
				action = (Action) clazz.newInstance();
				url = action.execute(req, form, mxc.getActionForward());
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
			RequestDispatcher rdis = req.getRequestDispatcher(url);
			rdis.forward(req, resp);

		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
